<?php
declare (strict_types = 1);

namespace app\common\model\User;

use think\Model;
use app\common\model\Region;

class Address extends Model
{
     // 用户收货地址
     protected $table = 'pre_user_address';
    
     // 定义追加字段列表 => 前后端分离项目
    protected $append = [
        // 地区字段
        'region_text',
        'region'
    ];

     // 定义不存在字段 region_text => RegionText
    public function getRegionTextAttr($value,$data)
    {
        $province = Region::where(['code' => $data['province']])->value('name');
        $city = Region::where(['code' => $data['city']])->value('name');
        $district = Region::where(['code' => $data['district']])->value('name');

        $region_text = '';
        if($province) {
            $region_text .= $province . '-';
        }
        if($city){
            $region_text .= $city . '-';
        }
        if($district) {
            $region_text .= $district;
        }
        return $region_text;
    }
    public function getRegionAttr($value, $data)
    {
        $province = Region::where(['code' => $data['province']])->find();
        $city = Region::where(['code' => $data['city']])->find();
        $district = Region::where(['code' => $data['district']])->find();
        $data = [
            $province['name'],
            $city['name'],
            $district['name'],
        ];
        return $data;
    }
}
